//
//  MahjongLoginVC.m
//  Mahjong
//
//  Created by 饶首建 on 17/6/28.
//  Copyright © 2017年 com.ikamobile.com. All rights reserved.
//

#import "MahjongLoginVC.h"
#import "QRCode.h"
#import "RandomArray.h"

#import "MahjongRuleSetVC.h"
#import "MahjongWaitingVC.h"
#import "MahjongMainVC.h"
#import "MahjongMainGameVC.h"

#import "SitPositionSetView.h"
#import "HWPopTool.h"


@interface MahjongLoginVC ()
@property (weak, nonatomic) IBOutlet UIView *inputView;
@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UIButton *sureBtn;
@property (weak, nonatomic) IBOutlet UIButton *toWechatBtn;
@property (weak, nonatomic) IBOutlet UIView *QRView;
@property (weak, nonatomic) IBOutlet UIImageView *QRCodeImageView;
@property (weak, nonatomic) IBOutlet UIButton *toInputBtn;


@end

static NSString *kUSERDEFAULTS_NICKNAME = @"kUserDefaults_nickname";

@implementation MahjongLoginVC

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(matchCallBack:) name:NOTIFICATION_MATCH_CALLBACK object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(meCallBack:) name:NOTIFICATION_ME_CALLBACK object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(matchReconnectCallBack:) name:NOTIFICATION_MATCH_RECONNECT_CALLBACK object:nil];
    
    [UIApplication sharedApplication].applicationSupportsShakeToEdit = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
    [UIApplication sharedApplication].applicationSupportsShakeToEdit = NO;
}

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
}

- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event {
}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    //设置pad的SitPostionType
    if (motion == UIEventSubtypeMotionShake && [[self getCurrentVC] isEqual:self]){
        SitPositionSetView *sitPositionSetView = [SitPositionSetView sitPositionSetView];
        [sitPositionSetView setDefault];
        [self showModalWithView:sitPositionSetView];
    }
    
}

- (UIViewController *)getCurrentVC{
    UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *topVC = appRootVC;
    if (topVC.presentedViewController) {
        topVC = topVC.presentedViewController;
    }
    return topVC;
}

- (void)showModalWithView:(UIView*)view{
    view.layer.cornerRadius = 10.f;
    view.layer.masksToBounds = YES;
    [HWPopTool sharedInstance].shadeBackgroundType = ShadeBackgroundTypeGradient;
    [HWPopTool sharedInstance].closeButtonType = ButtonPositionTypeNone;
    [[HWPopTool sharedInstance] showWithPresentView:view animated:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _inputView.hidden = YES;
    _QRView.hidden = NO;
    
    SitPositionType type = [[NSUserDefaults standardUserDefaults]integerForKey:NSUSERDEFAULTS_KEY_SITPOSITION];
    NSString *position = @"东";
    switch (type) {
        case SitPositionTypeWest:
            position = @"西";
            break;
        case SitPositionTypeSouth:
            position = @"南";
            break;
        case SitPositionTypeNorth:
            position = @"北";
            break;
            
        default:
            break;
    }
    
    _QRCodeImageView.image = [QRCode qrCode:_QRCodeImageView.frame.size.width url:NSStringFormat(@"%@/wechat/generateQR?clientId=%@&tableId=%@&position=%@",WECHAT_QRCODE_URL,[RandomArray idfaString],TABLE_ID,position)];
    
    
    
    NSString *nickName = [[NSUserDefaults standardUserDefaults]objectForKey:kUSERDEFAULTS_NICKNAME];
    _nameTF.text = nickName;
}

#pragma mark - notification

- (void)meCallBack:(NSNotification*)notification{
    NSDictionary *dic = notification.object;
    dic = [NSDictionary recursionResultJson4NullclassToNullstring:dic];
    [PlayerModel ownerInstance].playerId = dic[@"id"];
    [PlayerModel ownerInstance].playerName = dic[@"nickname"];
}

- (void)matchCallBack:(NSNotification*)notification{
    [self goPage:notification.object type:NO];
}

- (void)matchReconnectCallBack:(NSNotification*)notification{
    [self goPage:notification.object type:YES];
}

- (void)goPage:(NSDictionary *)dic type:(BOOL)isReconnect{
    dic = [NSDictionary recursionResultJson4NullclassToNullstring:dic];
    MatchModel *mm = [MatchModel parseDic:dic];
    
    if (isReconnect) {
        [PlayerModel ownerInstance].playerId = mm.me.playerId;
        [PlayerModel ownerInstance].playerName = mm.me.playerName;
    }
    
    BOOL flag = NO;
    for (PlayerModel *pm in mm.players) {
        if ([pm.playerId isEqualToString:[PlayerModel ownerInstance].playerId] && pm.isHost) {
            flag = YES;
            break;
        }
    }

    if (!mm.isSeted && flag) {
        MahjongRuleSetVC *vc = [[MahjongRuleSetVC alloc]init];
        vc.matchModel = mm;
        [self presentViewController:vc animated:YES completion:^{}];
    }else if (mm.players.count >= 4 && mm.isSeted) {
        MahjongMainGameVC *vc = [[MahjongMainGameVC alloc]init];
//        MahjongMainVC *vc = [[MahjongMainVC alloc]init];
        vc.matchModel = mm;
        [self presentViewController:vc animated:YES completion:^{}];
    }else {
        MahjongWaitingVC *vc = [[MahjongWaitingVC alloc]init];
        vc.matchModel = mm;
        [self presentViewController:vc animated:YES completion:^{}];
    }
}

#pragma mark - action

- (IBAction)toInputAction:(id)sender {
    _inputView.hidden = NO;
    _QRView.hidden = YES;
}

- (IBAction)toWechatAction:(id)sender {
    _inputView.hidden = YES;
    _QRView.hidden = NO;
}

- (IBAction)sureAction:(id)sender {
    NSString *nickname = [_nameTF.text stringByTrimmingCharactersInSet:[NSMutableCharacterSet whitespaceAndNewlineCharacterSet]];
    if (nickname.length == 0) {
        [Hud hudText:@"请填写昵称" inView:self.view];
        return;
    }
    
    [[NSUserDefaults standardUserDefaults]setObject:nickname forKey:kUSERDEFAULTS_NICKNAME];
    NSInteger position = [[NSUserDefaults standardUserDefaults]integerForKey:NSUSERDEFAULTS_KEY_SITPOSITION];
    NSString *pos = @"东";
    switch (position) {
        case SitPositionTypeEast:
            pos = @"东";
            break;
        case SitPositionTypeWest:
            pos = @"西";
            break;
        case SitPositionTypeSouth:
            pos = @"南";
            break;
        case SitPositionTypeNorth:
            pos = @"北";
            break;
            
        default:
            break;
    }
    NSString *url = [BASE_URL stringByAppendingPathComponent:API_POST_USERJOIN_MATCH];
    NSDictionary *param = @{
                            @"name":nickname,
                            @"tableId":TABLE_ID,
                            @"clientId":[RandomArray idfaString],
                            @"position":pos
                            };
    [HttpUtil sendRequestURL:url method:POST param:param success:^(id response) {
        NSString *errorStr = response[@"error"];
        if (errorStr.length) {
            [Hud hudText:errorStr inView:self.view];
        }
    } fail:^(NSString *errorStr) {
        [Hud hudText:errorStr inView:self.view];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
